package com.example.transaction_springboot.service;

import cn.hutool.crypto.SecureUtil;
import com.example.transaction_springboot.controller.request.AdminPageRequest;
import com.example.transaction_springboot.common.Page;
import com.example.transaction_springboot.controller.request.LoginRequest;
import com.example.transaction_springboot.controller.dto.AdminDTO;
import com.example.transaction_springboot.entity.Admin;
import com.example.transaction_springboot.exception.ServiceException;
import com.example.transaction_springboot.mapper.AdminMapper;
import com.example.transaction_springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AdminService {


    @Autowired
    private AdminMapper adminMapper;
    private final static String PASSWORD_SALT = "library";

    private String securePass(String password){
        return SecureUtil.md5(password + PASSWORD_SALT);
    }

    public List<Admin> list() {
        return adminMapper.listAdmins();
    }

    public Page<Admin> page(AdminPageRequest adminPageRequest) {
        Page<Admin> page = new Page<>();
        adminPageRequest.setPageNum((adminPageRequest.getPageNum() - 1) * adminPageRequest.getPageSize());
        List<Admin> adminList = adminMapper.selectByPage(adminPageRequest);
        Integer total = adminMapper.selectCountByPage(adminPageRequest);
        page.setList(adminList);
        page.setTotal(total);
        return page;
    }

    public void addAdmin(Admin admin) {
        //判断是否已经存在username
        if (adminMapper.selectByUsername(admin.getUsername()) != null) {
            throw new ServiceException("用户名已存在");
        }
        admin.setCreatetime(new Date());
        admin.setUpdatetime(new Date());
        admin.setPassword(securePass(admin.getPassword()));
        adminMapper.addAdmin(admin);
    }

    public Admin selectById(Integer id) {
        return adminMapper.selectById(id);
    }

    public void updateById(Admin admin) {
        admin.setUpdatetime(new Date());
        adminMapper.updateById(admin);
    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    public AdminDTO login(LoginRequest loginRequest) {
        loginRequest.setPassword(securePass(loginRequest.getPassword()));
        Admin admin = adminMapper.selectByUsernameAndPassword(loginRequest);
        if (admin == null) {
            throw new ServiceException("303","用户名或密码错误");
        }
        AdminDTO adminDTO = new AdminDTO(admin);
        adminDTO.setToken(TokenUtils.createToken(admin.getId().toString(),admin.getPassword()));
        return adminDTO;
    }

    public void changePassword(Admin admin) {
        admin.setPassword(securePass(admin.getPassword()));
        adminMapper.updatePassword(admin);
    }
}
